import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:management/model/gate_model.dart';
import 'package:management/model/msc_model.dart';
import 'package:management/utils/log_utils.dart';

///语音识别
class SpeechRecognize extends StatefulWidget {
  @override
  _SpeechRecognizeState createState() => _SpeechRecognizeState();
}

class _SpeechRecognizeState extends State<SpeechRecognize> {
  @override
  void initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back,
                size: 35,
              ),
              onPressed: () => Navigator.of(context).pop(),
            ),
            title: Text(
              "语音识别",
              style: TextStyle(fontSize: 30),
            ),
            centerTitle: true,
          ),
          body: SpeechRecognizeContent(),
        ),
        onWillPop: () async {
          Navigator.of(context).pop();
          return true;
        });
  }
}

class SpeechRecognizeContent extends StatefulWidget {
  @override
  _SpeechRecognizeContentState createState() => _SpeechRecognizeContentState();
}

class _SpeechRecognizeContentState extends State<SpeechRecognizeContent> {
  final String tag = "SpeechRecognizeContent";
  final TextEditingController recognizeResultController =
      TextEditingController();
  final TextEditingController passerbyController = TextEditingController();

  //语音识别相关通道
  final BasicMessageChannel mscChannel =
      BasicMessageChannel("MscChannel", StandardMessageCodec());

  bool isInit = false;

  Widget _buildContent() => Container(
        child: Column(
          children: [
            Container(
              height: 200,
              padding: EdgeInsets.all(10),
              child: TextFormField(
                controller: recognizeResultController,
                style: TextStyle(
                  fontSize: 25,
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 5,
                decoration: InputDecoration(hintText: "语音识别的结果将会显示在这里"),
              ),
            ),
            Container(
              width: 300,
              height: 60,
              margin: EdgeInsets.only(bottom: 20),
              child: TextFormField(
                controller: passerbyController,
                style: TextStyle(fontSize: 25),
                decoration: InputDecoration(
                  hintText: "请输入通行人员姓名",
                  border: OutlineInputBorder(),
                ),
              ),
            ),
            // MaterialButton(
            //   minWidth: 300,
            //   height: 50,
            //   color: Colors.blue,
            //   child: Text(
            //     "开始识别",
            //     style: TextStyle(
            //       color: Colors.white,
            //       fontSize: 25,
            //     ),
            //   ),
            //   onPressed: () async {
            //     //发送命令到android端进行语音识别
            //     var name = await mscChannel.send(
            //       MscChannelModel(message: {"cmd": "listen"}).toMap(),
            //     );
            //     MyLog.i("$name");
            //   },
            // ),
            Container(
              padding: EdgeInsets.only(top: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.warning_amber_sharp,
                    color: Colors.deepOrangeAccent,
                  ),
                  Text(
                    "开闸时注意检查通行安全",
                    style: TextStyle(
                      color: Colors.deepOrange,
                      fontSize: 18,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );

  @override
  void initState() {
    super.initState();

    mscChannel.setMessageHandler((message) async {
      MyLog.w("$tag mscChannel : $message");
      if (message is Map<Object,Object>) {
        Map<Object, Object> msg = message;
        bool receiveGate = msg["receiveGate"] as bool;
        if (receiveGate != null) setState(() => isInit = true);
        Object? recognizerResultObj = msg["recognizerResult"];
        String? recognizerResult;
        if (recognizerResultObj != null)
          recognizerResult = recognizerResultObj.toString();
        if (!TextUtil.isEmpty(recognizerResult)) {
          setState(() {
            recognizeResultController.text = recognizerResult!;
          });
          RecognizerResultModel.dealWithRecognizer(
            recognizerResult!,
            passerby: passerbyController.text,
          );
        }
      }
      return null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: FutureBuilder(
        future: isInit ? null : GateProvider.instance.getAllGate(),
        builder: (context, snap) {
          if (!isInit) {
            if (snap.hasData) {
              List<GateModel>? allGates = snap.data as List<GateModel>?;
              String data = "";
              allGates!.forEach((element) {
                //更新语音识别的词典由设备名称+/n 组成。e.g. "北门/n南门/n" 详见讯飞官方文档离线命令词识别
                //https://www.xfyun.cn/doc/asr/commandWord/Android-SDK.html
                data += "${element.deviceName}\n";
              });
              mscChannel.send(
                  MscChannelModel(message: {"cmd": "init", "data": data})
                      .toMap());
              MyLog.w("data:$data");
            } else {
              return Center(
                child: FutureBuilder(
                  future: Future.delayed(Duration(seconds: 3)),
                  builder: (context, snap) {
                    if (snap.connectionState == ConnectionState.done) {
                      return Text("还没有闸门的数据");
                    } else {
                      return CircularProgressIndicator();
                    }
                  },
                ),
              );
            }
          }
          return _buildContent();
        },
      ),
    );
  }

  @override
  void dispose() {
    mscChannel.send(MscChannelModel(message: {"cmd": "dispose"}).toMap());
    super.dispose();
  }
}
